package com.bawei.module_notice.ui

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.base.BaseResponse
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.RequestEvent
import com.bawei.lib_common.base.state.Success
import com.bawei.module_notice.model.NoticeModel
import com.bawei.module_notice.model.NoticeNavigationItem
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class NoticeViewModel @Inject constructor(
    private val repository: NoticeRepository
) : BaseViewModel() {

    // 分页参数
    var currentPage = 1
    private val pageSize = 10
    private var isLoading = false
    private var isLastPage = false

    // 公告数据
    var notices: List<NoticeModel>? = null

    // 状态流（加载、成功、失败）
    private val _mNoticeState = MutableStateFlow<RequestEvent>(Loading)
    val mNoticeState = _mNoticeState.asStateFlow()

    // 下拉刷新（重置页码）
    fun refresh() {
        currentPage = 1
        isLastPage = false
        fetchData()
    }

    // 上拉加载（页码+1）
    fun loadMore() {
        if (isLoading || isLastPage) return
        currentPage++
        fetchData()
    }

    // 核心请求方法
    private fun fetchData() {
        isLoading = true
        _mNoticeState.value = Loading
        viewModelScope.launch {
            try {
                repository.fetchAnnouncements(currentPage, pageSize)
                    .collect { flowResponse -> // 收集Flow结果
                        val response = flowResponse // 此时才是真实的BaseResponse
                        if (currentPage == 1) {
                            notices = response.data // 假设BaseResponse含data字段
                        } else {
                            notices = notices.orEmpty() + response.data
                        }
                        isLastPage = response.data.size < pageSize
                        _mNoticeState.value = Success
                    }
            } catch (e: Exception) {
                if (currentPage > 1) currentPage--
                _mNoticeState.value = Failed(e.message ?: "加载失败")
            } finally {
                isLoading = false
                _mNoticeState.value = Success // 必须结束加载
            }
        }
    }
}






